package com.lpl.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lpl.mapper.loginma;
import com.lpl.polo.hous;
import com.lpl.polo.result;
import com.lpl.polo.user;
import com.lpl.service.loginin;
import com.lpl.util.Httputil;

import com.lpl.util.jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class loginimpl implements loginin {
//    登录逻辑向微信发送请求
@Value("${weixin.appid}")
private  String appid;
@Value("${weixin.secret}")
private  String secret;
@Autowired
    private loginma loginma;
    @Override
    public result serLogin(String code) {
        String url="https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code" ;
        String repliceUrl = url.replace("{0}",appid).replace("{1}",secret).replace("{2}",code);
     //发送请求
       String res= Httputil.get(repliceUrl,null);

        JSONObject jsonObject = JSON.parseObject(res);
//        成功标识
        String openids = jsonObject.getString("openid");
//        小程序请求成功继续，把openid存入数据库
        if(openids!=null){
//  生成jwt
//            String openid = jsonObject.getString("openid");
//生成token
            Map<String,Object> clamis =new HashMap<>();
            clamis.put("id",openids);
            clamis.put("user","微信用户");
           String toKen= jwts.genToken(clamis);




//先看数据库是否已经有了对应的用户，有的话登录，没有注册在登陆
          user u =  loginma.selectUser(openids);

          if(u==null){
              //        用户的唯一id存入数据库
            loginma.daologin(openids);
              return result.success(toKen);
          }
            return  result.success(toKen);


        }
//        失败返回失败
        else {

            return  result.error("登录失败");

        }


    }

    @Override
    public result serLogins(hous conter) {

        //生成token
        Map<String,Object> clamis =new HashMap<>();
        clamis.put("id","后台");
        clamis.put("user","微信用户");
        String toKen= jwts.genToken(clamis);
        return result.success(toKen);
    }
}
